package db

import (
	"gitee.com/alex_li/beacon-config/internal/db/model"
	"github.com/lishimeng/app-starter"
	persistence "github.com/lishimeng/go-orm"
)

func GetDeviceList(pageNo int, pageSize int, nameFilter string) (devices []model.Device, err error) {
	if pageNo <= 0 {
		return
	}
	if pageSize <= 0 {
		return
	}
	from := (pageNo - 1) * pageSize
	var q = app.GetOrm().Context.
		QueryTable(new(model.Device)).
		OrderBy("DeviceID")
	if len(nameFilter) > 0 {
		q = q.Filter("DeviceName__contains", nameFilter)
	}
	_, err = q.Offset(from).Limit(pageSize).All(&devices)
	return
}

func UpdateDeviceName(id int, name string) (err error) {

	err = app.GetOrm().Transaction(func(ctx persistence.TxContext) (e error) {
		d := model.Device{DeviceID: id, DeviceName: name}
		_, e = ctx.Context.Update(&d, "device_name")
		return
	})
	return
}
